from rest_framework.response import Response

from meiduo_mall.apps.verifications import serializers
from meiduo_mall.third_libs.yuntongxun.sms import CCP
from . import constants

import random

from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from celery_tasks.sms.tasks import send_sms_code
from django.http import HttpResponse
from meiduo_mall.third_libs.captcha.captcha import captcha
from django_redis import get_redis_connection


class ImageCodeView(APIView):
    """提供图片验证码"""
    def get(self, request, image_code_id):
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 存储图片验证码的内容
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 响应图片验证码的图片数据
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(GenericAPIView):
    """提供短信验证码"""
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self, request, mobile):
        # 生成短信验证码
        # 判断短信验证码，是否在60s内
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 保存短信验证码并且发送记录
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # redis管道，可以将多个redis指令集成到一起执行，不用多次访问redis数据库
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # 记录发送短信的标记
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        print(sms_code)
        # 发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SMS_SEND_TEMPLATE_ID)

        # sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        # send_sms_code.delay(mobile, sms_code)

        return Response({'message': 'ok'})








